package com.xiaoming.core.factory;


import com.xiaoming.core.annotation.Autowired;
import com.xiaoming.core.annotation.Component;
import com.xiaoming.core.annotation.Transactional;
import com.xiaoming.core.utils.TransactionManager;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class ProxyFactory {
    @Autowired
    private TransactionManager transactionManager;

    /***
     * 获取代理对象
     * @param obj
     * @return
     */
    public Object getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                (Object proxy, Method method, Object[] args) -> {
                    Transactional annotation = obj.getClass().getAnnotation(Transactional.class);
                    Object result = null;
                    if (annotation != null) {
                        try {
                            transactionManager.beginTransaction();
                            result = method.invoke(obj, args);
                            transactionManager.commit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            transactionManager.rollback();
                            throw e;
                        }
                    } else {
                        result = method.invoke(obj, args);
                    }
                    return result;
                }
        );
    }
}
